package io.renren.modules.erp.controller;

import com.alibaba.fastjson.JSONObject;
import io.renren.common.annotation.SysLog;
import io.renren.common.constants.BusinessConstants;
import io.renren.common.constants.ExceptionConstants;
import io.renren.common.exception.BusinessParamCheckingException;
import io.renren.common.utils.Constants;
import io.renren.common.utils.QueryUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import io.renren.modules.erp.entity.*;
import io.renren.modules.erp.service.AccountHeadService;
import io.renren.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jishenghua 752*718*920
 */
@RestController
@RequestMapping(value = "/accountHead")
public class AccountHeadController  extends AbstractController {
    private Logger logger = LoggerFactory.getLogger(AccountHeadController.class);

    @Autowired
    private AccountHeadService accountHeadService;

    @GetMapping(value = "/list")
    @RequiresPermissions("accountHead:list")
    public R getAccountHeadList(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String type = StringUtil.getInfo(search, "type");
        String roleType = StringUtil.getInfo(search, "roleType");
        String billNo = StringUtil.getInfo(search, "billNo");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));
        String order = QueryUtils.order(params);
        return R.ok().put("data",accountHeadService.select(type, roleType, billNo, beginTime, endTime, currPage, pageSize,1L));
    }


    //收款单列表(包含预收付款)
    @GetMapping(value = "/getReceiptList")
//    @RequiresPermissions("accountHead:list")
    public R getReceiptList(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String billNo = StringUtil.getInfo(search, "billNo");
        String roleType = StringUtil.getInfo(search, "roleType");
        String type = StringUtil.getInfo(search, "type");

        //审核状态
        String status = StringUtil.getInfo(search, "status");
        //客户
        String organName = StringUtil.getInfo(search, "organName");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
       //收款金额最小值
        String totalPriceMin =  StringUtil.getInfo(search, "totalPriceMin");
        String totalPriceMax =  StringUtil.getInfo(search, "totalPriceMax");

        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));
//        String order = QueryUtils.order(params);
        return R.ok().put("data",accountHeadService.getReceiptList(billNo,type,status, organName, roleType, beginTime, endTime, currPage, pageSize,getUserId(),totalPriceMin,totalPriceMax));
    }




        //付款单列表(包含预收付款)
    @GetMapping(value = "/getPaymentList")
//    @RequiresPermissions("accountHead:list")
    public R getPaymentList(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String billNo = StringUtil.getInfo(search, "billNo");
        //全部数据
        String roleType = StringUtil.getInfo(search, "roleType");
        //付款
        String type = StringUtil.getInfo(search, "type");

        //审核状态
        String status = StringUtil.getInfo(search, "status");
        //供应商
        String organName = StringUtil.getInfo(search, "organName");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        //收款金额最小值
        String totalPriceMin =  StringUtil.getInfo(search, "totalPriceMin");
        String totalPriceMax =  StringUtil.getInfo(search, "totalPriceMax");

        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));

        //付款类型
        String paymentType = StringUtil.getInfo(search, "paymentType");
//        String order = QueryUtils.order(params);
        return R.ok().put("data",accountHeadService.getPaymentList(billNo,type,status, organName, roleType, beginTime, endTime, currPage, pageSize,getUserId(),totalPriceMin,totalPriceMax,paymentType));
    }



    //收   核销单列表Verification
    @GetMapping(value = "/getVerificationList")
//    @RequiresPermissions("accountHead:list")
    public R getVerificationList(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String billNo = StringUtil.getInfo(search, "billNo");
        //全部数据
        String roleType = StringUtil.getInfo(search, "roleType");
        //核销
        String type = StringUtil.getInfo(search, "type");

        //审核状态，单据状态  待核销，已核销
        String status = StringUtil.getInfo(search, "status");
        //客户
        String organName = StringUtil.getInfo(search, "organName");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        //核销金额最小值喝最大
        String totalPriceMin =  StringUtil.getInfo(search, "totalPriceMin");
        String totalPriceMax =  StringUtil.getInfo(search, "totalPriceMax");

        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));
        //业务项目
        String serviceType =  StringUtil.getInfo(search, "serviceType");

//        String order = QueryUtils.order(params);
        return R.ok().put("data",accountHeadService.getVerificationList(billNo,type,status, organName, roleType, beginTime, endTime, currPage, pageSize,getUserId(),totalPriceMin,totalPriceMax,serviceType));
    }




    //应收帐列表(包含预收付款)receivable
    @GetMapping(value = "/getReceivableList")
//    @RequiresPermissions("accountHead:list")
    public R getReceivableList(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
//        String billNo = StringUtil.getInfo(search, "billNo");
        //全部数据
        String roleType = StringUtil.getInfo(search, "roleType");
        //type 为 应收账
        String type = StringUtil.getInfo(search, "type");

        //客户
        String organName = StringUtil.getInfo(search, "organName");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        //业务员
        String userName = StringUtil.getInfo(search, "userName");
          //源单编号
        String receivablesBillno = StringUtil.getInfo(search, "receivablesBillno");


        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));
//        String order = QueryUtils.order(params);
        return R.ok().put("data",accountHeadService.getReceivableList(type, organName, roleType, beginTime, endTime, currPage, pageSize,userName,receivablesBillno,getUserId()));
    }

    //应付帐列表
    @GetMapping(value = "/getAccountableList")
//    @RequiresPermissions("accountHead:list")
    public R getAccountableList(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
//       String billNo = StringUtil.getInfo(search, "billNo");
        //全部数据
        String roleType = StringUtil.getInfo(search, "roleType");
        //type 为 应付账
        String type = StringUtil.getInfo(search, "type");

        //客户
        String organName = StringUtil.getInfo(search, "organName");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        //业务员
        String userName = StringUtil.getInfo(search, "userName");
        //源单编号
        String accountpayBillno = StringUtil.getInfo(search, "accountpayBillno");


        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));
//        String order = QueryUtils.order(params);
        return R.ok().put("data",accountHeadService.getAccountableList(type, organName, roleType, beginTime, endTime, currPage, pageSize,userName,accountpayBillno,getUserId()));
    }



    /**
     * 新增单据主表及单据子表信息     收款单/预收款单
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addReceiptAndDetail")
    public Object addReceiptAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        String beanJson = body.getInfo();
        String rows = body.getRows();
        String numbers = body.getNumbers();

        accountHeadService.addReceiptAndDetail(beanJson,rows,getTenantId(), request,getUserId(),numbers);

        return R.ok();

    }


    /**
     * 新增单据主表及单据子表信息     付款单/预付款单
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addPaymentAndDetail")
    public Object addPaymentAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        String beanJson = body.getInfo();
        String rows = body.getRows();
        String numbers = body.getNumbers();

        accountHeadService.addPaymentAndDetail(beanJson,rows,getTenantId(), request,getUserId(),numbers);

        return R.ok();

    }



    /**
     * 新增单据主表及单据子表信息     销向核销单
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addVerification")
    public Object addVerification(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        String beanJson = body.getInfo();
//        String rows = body.getRows();
        String numbers = body.getNumbers();

        accountHeadService.addVerification(beanJson,getTenantId(), request,getUserId(),numbers);

        return R.ok();

    }



    /**
     * 更新单据主表及单据子表信息  收款单的修改
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/updateReceiptAndDetail")
//    @RequiresPermissions("depotHead:update")
    public R updateReceiptAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        Long id = body.getId();
        String beanJson = body.getInfo();
        String rows = body.getRows();
        String numbers = body.getNumbers();

        accountHeadService.updateReceiptAndDetail(id,beanJson,rows,getTenantId(),request,getUserId(),numbers);
        return R.ok();
    }



    /**
     * 批量设置状态-审核或者反审核
     * @param request
     * @return
     */
    @PostMapping(value = "/batchSetStatus")
    public R batchSetStatus(@RequestBody AccountHead accountHead,
                            HttpServletRequest request) throws Exception{
        String status=accountHead.getStatus();
        String accountHeadIDs=accountHead.getAccountHeadIDs();
        int res = accountHeadService.batchSetStatus(status, accountHeadIDs);
        if(res > 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }


    @SysLog("保存")
    @PostMapping("/save")
    public R save(@RequestBody AccountHead accountHead){
        accountHeadService.save(accountHead);
        return R.ok();
    }
    /**
     * 获取最大的id
     * @param request
     * @return
     */
    @GetMapping(value = "/getMaxId")
    public R getMaxId(HttpServletRequest request)throws Exception {
        Long maxId = accountHeadService.getMaxId();
        return R.ok().put("maxId", maxId);
    }

    /**
     * 查询单位的累计应收和累计应付，收预付款不计入此处
     * @param supplierId
     * @param endTime
     * @param supType
     * @param request
     * @return
     */
    @GetMapping(value = "/findTotalPay")
    public R findTotalPay(@RequestParam("supplierId") Integer supplierId,
                          @RequestParam("endTime") String endTime,
                          @RequestParam("supType") String supType,
                          HttpServletRequest request)throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject outer = new JSONObject();
        BigDecimal sum = accountHeadService.findTotalPay(supplierId, endTime, supType);
        outer.put("getAllMoney", sum);
        map.put("rows", outer);
        return R.ok().put("data", map);
    }

    /**
     * 根据编号查询单据信息
     * @param billNo
     * @param request
     * @return
     */
    @GetMapping(value = "/getDetailByNumber")
    public R getDetailByNumber(@RequestParam("billNo") String billNo,
                               HttpServletRequest request)throws Exception {

        AccountHeadVo4ListEx ahl = new AccountHeadVo4ListEx();
        List<AccountHeadVo4ListEx> list = accountHeadService.getDetailByNumber(billNo);
        if(list.size() == 1) {
            ahl = list.get(0);
        }
        return R.ok().put("data" , ahl);
    }

    /**
     *  批量删除账户信息
     * create time: 2019/3/29 10:49
     * @Param: ids
     * @return java.lang.Object
     */
    @RequestMapping(value = "/batchDeleteAccountHeadByIds")
//    @RequiresPermissions("accountHead:delete")
    public Object batchDeleteAccountHeadByIds(@RequestParam("ids") String ids,@RequestParam(value="deleteType",
            required =false,defaultValue= BusinessConstants.DELETE_TYPE_NORMAL)String deleteType) throws Exception {

        accountHeadService.batchDeleteAccountHeadByIds(ids,getUserId());
        return R.ok();
    }


    @PostMapping(value = "/add")
    public R insert(@RequestBody String beanJson, HttpServletRequest request) throws Exception{
            if(1==accountHeadService.insertAccountHead(beanJson, request,getUserId())){

                return R.ok();
        }else{
            return R.error();
        }
    }

    @PostMapping(value = "/update")
    @RequiresPermissions("accountHead:update")
    public R update(@RequestBody String beanJson, Long id, HttpServletRequest request)throws Exception {
        if(1==accountHeadService.updateAccountHead(beanJson, id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/delete")
    public R delete(@RequestParam("id") Long id, HttpServletRequest request)throws Exception {
        if(1==accountHeadService.deleteAccountHead(id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/batchDelete")
    public R batchDelete(@RequestParam("ids") String ids, HttpServletRequest request)throws Exception {
        if(1==accountHeadService.batchDeleteAccountHead(ids, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/checkIsNameExist")
    public R checkIsNameExist(@RequestParam("id") Long id, @RequestParam("name") String name)throws Exception {
        if(0<accountHeadService.checkIsNameExist(id, name)){
            return R.ok();
        }else{
            return R.error();
        }
    }
}
